<template>
  <div class="flex-1 bg-white rounded-lg mx-2 my-2 flex flex-col overflow-hidden">
    <div class="px-5 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center">
      <h2 class="text-lg font-semibold text-gray-800 m-0">简历编辑</h2>
      <div class="flex items-center gap-3">
        <!-- 折叠控制按钮 -->
        <div class="flex items-center gap-2">
          <button
            class="text-xs text-gray-600 hover:text-gray-800 px-2 py-1 rounded hover:bg-gray-200 transition-colors"
            title="全部展开"
            @click="expandAll"
          >
            全部展开
          </button>
          <button
            class="text-xs text-gray-600 hover:text-gray-800 px-2 py-1 rounded hover:bg-gray-200 transition-colors"
            title="全部折叠"
            @click="collapseAll"
          >
            全部折叠
          </button>
        </div>
        
        <!-- 保存状态 -->
        <div v-if="saving" class="flex items-center">
          <span class="text-sm text-blue-500 flex items-center gap-1.5">
            <span class="w-3 h-3 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
            保存中...
          </span>
        </div>
      </div>
    </div>

    <div class="flex-1 p-5 overflow-y-auto">
      <div class="space-y-6">
        <DraggableSection
          v-for="(section, index) in sections"
          :key="section.id"
          :section-id="section.id"
          :index="index"
          @drag-start="handleDragStart"
          @drag-end="handleDragEnd"
          @drag-over="handleDragOver"
          @drop="handleDrop"
        >
          <!-- 基本信息 -->
          <CollapsibleSection
            v-if="section.id === 'basic-info'"
            :title="section.title"
            :item-count="1"
            :section-id="section.id"
            :external-state="true"
          >
            <BasicInfoForm :resume-data="resumeData" />
          </CollapsibleSection>
          
          <!-- 教育经历 -->
          <CollapsibleSection
            v-if="section.id === 'education'"
            :title="section.title"
            :item-count="resumeData.education.length"
            :section-id="section.id"
            :external-state="true"
          >
            <template #actions>
              <button
                class="text-blue-600 hover:text-blue-800 text-sm font-medium"
                @click="$emit('add-education')"
              >
                + 添加
              </button>
            </template>
            <EducationForm
              :resume-data="resumeData"
              @add-education="$emit('add-education')"
              @remove-education="$emit('remove-education', $event)"
            />
          </CollapsibleSection>
          
          <!-- 工作经历 -->
          <CollapsibleSection
            v-if="section.id === 'work-experience'"
            :title="section.title"
            :item-count="resumeData.workExperience.length"
            :section-id="section.id"
            :external-state="true"
          >
            <template #actions>
              <button
                class="text-blue-600 hover:text-blue-800 text-sm font-medium"
                @click="$emit('add-work')"
              >
                + 添加
              </button>
            </template>
            <WorkExperienceForm
              :resume-data="resumeData"
              @add-work="$emit('add-work')"
              @remove-work="$emit('remove-work', $event)"
            />
          </CollapsibleSection>
          
          <!-- 项目经验 -->
          <CollapsibleSection
            v-if="section.id === 'projects'"
            :title="section.title"
            :item-count="resumeData.projects.length"
            :section-id="section.id"
            :external-state="true"
          >
            <template #actions>
              <button
                class="text-blue-600 hover:text-blue-800 text-sm font-medium"
                @click="$emit('add-project')"
              >
                + 添加
              </button>
            </template>
            <ProjectForm
              :resume-data="resumeData"
              @add-project="$emit('add-project')"
              @remove-project="$emit('remove-project', $event)"
            />
          </CollapsibleSection>
          
          <!-- 专业技能 -->
          <CollapsibleSection
            v-if="section.id === 'skills'"
            :title="section.title"
            :item-count="resumeData.skills.length"
            :section-id="section.id"
            :external-state="true"
          >
            <template #actions>
              <button
                class="text-blue-600 hover:text-blue-800 text-sm font-medium"
                @click="$emit('add-skill')"
              >
                + 添加
              </button>
            </template>
            <SkillsForm
              :resume-data="resumeData"
              @add-skill="$emit('add-skill')"
              @remove-skill="$emit('remove-skill', $event)"
            />
          </CollapsibleSection>
          
          <!-- 自我评价 -->
          <CollapsibleSection
            v-if="section.id === 'self-evaluation'"
            :title="section.title"
            :item-count="resumeData.selfEvaluation ? 1 : 0"
            :section-id="section.id"
            :external-state="true"
          >
            <SelfEvaluationForm :resume-data="resumeData" />
          </CollapsibleSection>
        </DraggableSection>
      </div>

      <!-- 操作按钮（不可拖拽） -->
      <div class="mt-8">
        <ActionButtons
          :saving="saving"
          :exporting="exporting"
          :show-preview="showPreview"
          @save="$emit('save')"
          @toggle-preview="$emit('toggle-preview')"
          @export-pdf="$emit('export-pdf')"
        />
      </div>
    </div>

    <!-- 拖拽提示 -->
    <DragHint
      :show="showDragHint"
      :title="dragHintTitle"
      :message="dragHintMessage"
      @hide="showDragHint = false"
    />

    <!-- 拖拽引导 -->
    <DragGuide
      :show="showDragGuide"
      @hide="hideGuide"
      @dont-show-again="dontShowGuideAgain"
    />
  </div>
</template>

<script setup lang="ts">
import BasicInfoForm from './BasicInfoForm.vue'
import EducationForm from './EducationForm.vue'
import WorkExperienceForm from './WorkExperienceForm.vue'
import ProjectForm from './ProjectForm.vue'
import SkillsForm from './SkillsForm.vue'
import SelfEvaluationForm from './SelfEvaluationForm.vue'
import ActionButtons from './ActionButtons.vue'
import DraggableSection from './DraggableSection.vue'
import DragHint from './DragHint.vue'
import DragGuide from './DragGuide.vue'
import CollapsibleSection from './CollapsibleSection.vue'
import { useCollapseState } from '~/composables/useCollapseState'

interface ResumeData {
  name: string
  phone: string
  email: string
  hometown: string
  currentResidence: string
  jobIntention: string
  education: Array<{
    school: string
    major: string
    degree: string
    startDate: string
    endDate: string
  }>
  workExperience: Array<{
    company: string
    position: string
    startDate: string
    endDate: string
    description: string
  }>
  projects: Array<{
    name: string
    role: string
    duration: string
    description: string
  }>
  skills: Array<{
    description: string
  }>
  selfEvaluation: string
}

interface Props {
  resumeData: ResumeData
  saving: boolean
  exporting: boolean
  showPreview: boolean
}

defineProps<Props>()

const emit = defineEmits<{
  'add-education': []
  'remove-education': [index: number]
  'add-work': []
  'remove-work': [index: number]
  'add-project': []
  'remove-project': [index: number]
  'add-skill': []
  'remove-skill': [index: number]
  save: []
  'toggle-preview': []
  'export-pdf': []
  'reorder-sections': [newOrder: string[]]
}>()

// 定义可拖拽的模块顺序
const sections = ref([
  { id: 'basic-info', title: '基本信息' },
  { id: 'education', title: '教育经历' },
  { id: 'work-experience', title: '工作经历' },
  { id: 'projects', title: '项目经验' },
  { id: 'skills', title: '专业技能' },
  { id: 'self-evaluation', title: '自我评价' }
])

// 拖拽状态
const draggedIndex = ref(-1)
const draggedOverIndex = ref(-1)

// 拖拽提示状态
const showDragHint = ref(false)
const dragHintTitle = ref('')
const dragHintMessage = ref('')

// 拖拽引导状态
const showDragGuide = ref(false)

// 折叠状态管理
const { initCollapseStates, expandAll, collapseAll } = useCollapseState()

// 初始化折叠状态
onMounted(() => {
  initCollapseStates()
})

// 处理拖拽开始
const handleDragStart = (index: number) => {
  draggedIndex.value = index
  const section = sections.value[index]
  
  // 显示拖拽提示
  showDragHint.value = true
  dragHintTitle.value = '开始拖拽'
  dragHintMessage.value = `正在拖拽 "${section.title}" 模块，将其移动到其他位置`
}

// 处理拖拽结束
const handleDragEnd = () => {
  draggedIndex.value = -1
  draggedOverIndex.value = -1
  showDragHint.value = false
}

// 处理拖拽经过
const handleDragOver = (index: number) => {
  draggedOverIndex.value = index
  
  if (draggedIndex.value !== -1 && draggedIndex.value !== index) {
    const draggedSection = sections.value[draggedIndex.value]
    const targetSection = sections.value[index]
    
    showDragHint.value = true
    dragHintTitle.value = '放置位置'
    dragHintMessage.value = `将 "${draggedSection.title}" 移动到 "${targetSection.title}" 的位置`
  }
}

// 处理放置
const handleDrop = (fromIndex: number, toIndex: number) => {
  console.log('EditorPanel handleDrop:', { fromIndex, toIndex })
  
  if (fromIndex === toIndex) return
  
  // 重新排序sections
  const newSections = [...sections.value]
  const [movedSection] = newSections.splice(fromIndex, 1)
  
  // 调整目标索引（如果拖拽到后面，需要减1因为已经移除了一个元素）
  const adjustedToIndex = toIndex > fromIndex ? toIndex - 1 : toIndex
  newSections.splice(adjustedToIndex, 0, movedSection)
  
  console.log('重新排序后的sections:', newSections.map(s => s.id))
  
  sections.value = newSections
  
  // 通知父组件重新排序
  const newOrder = newSections.map(s => s.id)
  console.log('发送给父组件的顺序:', newOrder)
  emit('reorder-sections', newOrder)
  
  // 重置拖拽状态
  draggedIndex.value = -1
  draggedOverIndex.value = -1
  
  // 添加成功反馈
  showDragHint.value = true
  dragHintTitle.value = '移动成功'
  dragHintMessage.value = `"${movedSection.title}" 已成功移动到位置 ${adjustedToIndex + 1}`
  
  // 3秒后自动隐藏提示
  setTimeout(() => {
    showDragHint.value = false
  }, 2000)
}

// 隐藏拖拽引导
const hideGuide = () => {
  showDragGuide.value = false
}

// 不再显示引导
const dontShowGuideAgain = () => {
  showDragGuide.value = false
  // 这里可以保存到本地存储，表示用户已经看过引导
  localStorage.setItem('drag-guide-seen', 'true')
}

// 检查是否需要显示引导
onMounted(() => {
  const guideSeen = localStorage.getItem('drag-guide-seen')
  if (!guideSeen) {
    // 延迟显示引导，让用户先看到界面
    setTimeout(() => {
      showDragGuide.value = true
    }, 1000)
  }
})
</script>
